package com.ict.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author wujinpeng
 * @version 1.0
 * @date 2024/8/31 20:55
 * @description 自定义请求重试机制
 */
@Slf4j
public class RetryInterceptor implements ClientHttpRequestInterceptor {

    private final int maxRetries;

    public RetryInterceptor(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request,
                                        byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        int retryCount = 0;
        while (retryCount < maxRetries) {
            try {
                return execution.execute(request, body);
            } catch (IOException e) {
                retryCount++;
                if (retryCount >= maxRetries) {
                    throw e;
                }
                // Optionally, add a delay between retries
                try {
                    Thread.sleep(1000); // 1 second delay
                    log.warn("Failed request url:{}, retry count:{}", request.getURI(), retryCount);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        throw new IOException("Failed after " + maxRetries + " retries");
    }

}
